package com.zhangyj.impl.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.zhangyj.dao.ProduceDao;
import com.zhangyj.db.DBUtil;
import com.zhangyj.entitis.ProduceType;

public class ProduceDaoImpl implements ProduceDao {
	
	public List<ProduceType> getTypes() throws SQLException {
		List<ProduceType> list = new ArrayList<ProduceType>();
		Connection conn = null;
		try {
			conn = DBUtil.getConnection();
			String sql = "SELECT cplh,cplm FROM producefl";
			PreparedStatement ps = conn.prepareStatement(sql);
			ResultSet rst = ps.executeQuery();
			while (rst.next()) {
				ProduceType pt = new ProduceType(rst.getString(1), rst.getString(2));
				list.add(pt);
			}
			rst.close();
			ps.close();
		} finally {
			if (conn != null) {
				conn.close();
			}
		}
		return list;
	}

	public ProduceType loadType(String typeId) throws SQLException {
		Connection conn = null;
		ProduceType pt = null;
		try {
			conn = DBUtil.getConnection();
			String sql = "SELECT cplm FROM producefl WHERE cplh=? ";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, typeId);
			ResultSet rst = ps.executeQuery();
			while (rst.next()) {
				pt = new ProduceType(typeId, rst.getString(1));
			}
			rst.close();
			ps.close();
		} finally {
			if (conn != null) {
				conn.close();
			}
		}
		return pt;
	}

	public ProduceType delType(String typeId) throws SQLException {
		Connection conn = null;
		ProduceType pt = null;
		try {
			conn = DBUtil.getConnection();
			String sql = "DELETE FROM producefl WHERE cplh=? ";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, typeId);
			ps.executeUpdate();
			ps.close();
		} finally {
			if (conn != null) {
				conn.close();
			}
		}
		return pt;
	}

	public void saveType(ProduceType pt, boolean isUpdate) throws SQLException {
		Connection conn = null;
		try {
			conn = DBUtil.getConnection();
			String sql = "INSERT INTO producefl (cplm,cplh)VALUES(?,?)";
			if (isUpdate) {
				sql = "UPDATE producefl SET cplm=? WHERE cplh=?";
			}

			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, pt.getCplm());
			ps.setString(2, pt.getCplh());
			ps.execute();
			ps.close();
		} finally {
			if (conn != null) {
				conn.close();
			}
		}
	}
}
